package top.yuanao.portscan;

import java.io.IOException;
import java.net.Socket;
import java.util.ArrayList;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * utils.java
 *
 * @author Yuanao
 * @date 2021/12/21 18:50
 */
public class Utils {



    public static volatile ArrayList<String> list = new ArrayList<>();


    /**
     * 现将文本添加到列表,然后再刷新
     */
    public static synchronized void refreshShowText(String text) {
        list.add(text);
        refreshShowText();
    }

    /**
     * 将首页的输出刷新一次
     */
    public static synchronized void refreshShowText() {
        Main.showText.setText("");

        for (int i = list.size() -1; i > -1; i--) {
            Main.showText.append(list.get(i) + "\n");
        }

    }






    /**
     * 多线程的方式扫描端口
     * 或造成端口号无序
     * @param domain    主机域名或者IP
     * @param StartPort 开始端口
     * @param endPort   结束端口
     */
    public static void portScanMultithreading(String domain, int StartPort, int endPort) {

        //先清空列表
        list.clear();

        refreshShowText("开始扫描端口......");

        //创建线程池
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(5000, 5000, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<>());

        for (int i = StartPort; i <= endPort; i++) {

            int port = i;
            threadPoolExecutor.execute(() -> {
                try {
                    Socket socket = new Socket(domain, port);
                    socket.close();
                    socket = null;
                    refreshShowText(domain + ":" + port);
                } catch (IOException e) {
                   //连接失败,端口没有打开
                }
            });

        }

        //死循环检测所有线程结束
        while (true) {
            if (threadPoolExecutor.getActiveCount() == 0) {
                refreshShowText("扫描完成");
                threadPoolExecutor = null;
                System.gc();
                return;
            }
        }

    }

}
